package com.lxy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxy.pojo.Book;
import com.lxy.service.BookService;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Arrays;

@Controller
public class BookController {
    @Autowired
    private BookService bookService;

    @RequestMapping("/book")
    public String book(Book book, Model model, @RequestParam(defaultValue = "1")Integer pageNum){
        Page<Book> page = new Page<>(pageNum,3);
        LambdaQueryWrapper<Book> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(book.getName()),Book::getName,book.getName());
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(book.getAuthor()),Book::getAuthor,book.getAuthor());
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(book.getCategory()),Book::getCategory,book.getCategory());
        bookService.page(page,lambdaQueryWrapper);
        model.addAttribute("page",page);
        return "book";
    }
    @PostMapping("/del")
    public String del(Integer[] ids){
        bookService.removeByIds(Arrays.asList(ids));
        return "redirect:/book";
    }
    @PostMapping("/add")
    public String add(Book book){
        bookService.saveOrUpdate(book);
        return "redirect:/book";
    }
    @GetMapping("/toAdd")
    public String toAdd(){
        return "add";
    }
    @GetMapping("/toUp")
    public String toUp(Integer id,Model model){
        Book byId = bookService.getById(id);
        model.addAttribute("b",byId);
        return "update";
    }
}